package com.cxh.rmsq.ui.fragment.self

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.cretin.www.cretinautoupdatelibrary.model.DownloadInfo
import com.cretin.www.cretinautoupdatelibrary.utils.AppUpdateUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.db.model.FriendShipInfo
import com.cxh.rmsq.db.model.FriendStatus
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.model.Resource
import com.cxh.rmsq.model.Status
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.activity.AddFriendActivity
import com.cxh.rmsq.ui.activity.CreateGroupActivity
import com.cxh.rmsq.ui.activity.ScanActivity
import com.cxh.rmsq.ui.activity.SealSearchActivity
import com.cxh.rmsq.ui.activity.SelectCreateGroupActivity
import com.cxh.rmsq.ui.activity.SelectSingleFriendActivity
import com.cxh.rmsq.ui.adapter.models.ListItemModel
import com.cxh.rmsq.ui.dialog.MorePopWindow
import com.cxh.rmsq.ui.fragment.BaseFragment
import com.cxh.rmsq.ui.fragment.MainContactsListFragment
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.jumpToAppStore
import com.cxh.rmsq.utils.log.SLog
import com.cxh.rmsq.utils.permission.AppPermissionUtil
import com.cxh.rmsq.utils.permission.AppPermissionUtil.OnPermissionListener
import com.cxh.rmsq.viewmodel.MainContactsListViewModel
import com.cxh.rmsq.viewmodel.MainViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.shape.view.ShapeTextView
import io.rong.imkit.picture.tools.ScreenUtils

/**
 * 消息、联系人合并
 */
class MsgHomeFragment : BaseFragment(), MorePopWindow.OnPopWindowItemClickListener {

    private lateinit var tabCommunity: TabLayout
    private lateinit var tvMarquee: TextView
    private var viewPager: ViewPager2? = null
    private var ivSearch: ImageView? = null
    private var ivAdd: ImageView? = null

    private val tabs = arrayOf("消息", "联系人")
    private val mFragments = ArrayList<Fragment>()
    private var mediator: TabLayoutMediator? = null
    private val REQUEST_START_CHAT = 0
    private val REQUEST_START_GROUP = 1
    var mainViewModel: MainViewModel? = null
    var countNum = 0
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }

    private var viewModels: MainContactsListViewModel? = null

    override fun getLayoutResId(): Int {
        return R.layout.fragment_msg_home
    }


    companion object {
        private const val RG_PARAM1 = "param1"

        @JvmStatic
        fun newInstance(contactNum: Int): MsgHomeFragment {
            val fragment = MsgHomeFragment()
            val args = Bundle()
            args.putInt(RG_PARAM1, contactNum)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        countNum = requireArguments().getInt(RG_PARAM1)

        initData()

        tvMarquee = view.findViewById(R.id.tvMarquee)
        tabCommunity = view.findViewById(R.id.tab_community)
        viewPager = view.findViewById(R.id.view_pager)
        ivSearch = view.findViewById(R.id.iv_search)
        ivAdd = view.findViewById(R.id.iv_add)

        tvMarquee.text =
            "警惕诈骗，不轻信不转账，守好钱袋！非本平台转账视为自愿，风险自负，与本平台无关！"
        tvMarquee.isSelected = true //开启滚动

        initTab()

        ivSearch!!.setOnClickListener {
            val intent = Intent(activity, SealSearchActivity::class.java)
            startActivity(intent)
        }
        ivAdd!!.setOnClickListener {
            val morePopWindow = MorePopWindow(activity, this)
//            morePopWindow.showPopupWindow(ivAdd, 0.8f, -getXOffset(), 0)
            onAddFriendClick()
        }
    }

    private fun initTab() {
        mFragments.clear()

        mFragments.add(MessageListFragment())
        mFragments.add(MainContactsListFragment())

        //Adapter
        viewPager!!.adapter = object : FragmentStateAdapter(
            childFragmentManager,
            lifecycle
        ) {
            override fun createFragment(position: Int): Fragment {
                //FragmentStateAdapter内部自己会管理已实例化的fragment对象。
                // 所以不需要考虑复用的问题
                return mFragments[position]
            }

            override fun getItemCount(): Int {
                return mFragments.size
            }
        }
        //viewPager 页面切换监听监听
        viewPager!!.registerOnPageChangeCallback(changeCallback)
        //        binding.viewPager.setUserInputEnabled(false);
        //        binding.viewPager.setUserInputEnabled(false);
        viewPager!!.offscreenPageLimit = mFragments.size - 1

        mediator = TabLayoutMediator(
            tabCommunity, viewPager!!
        ) { tab, position -> //这里可以自定义TabView
            val customView = tab.customView
            if (customView == null) {
                tab.setCustomView(R.layout.tab_item_camp)
            }
            val tab_text = tab.customView!!.findViewById<TextView>(R.id.tab_text)
            val stv_dot = tab.customView!!.findViewById<ShapeTextView>(R.id.stv_dot)
            val tab_indicator =
                tab.customView!!.findViewById<ImageView>(R.id.tab_indicator)
            if (position < tabs.size) {
                tab_text.text = tabs[position]
            }
    //            if (position == 1 && countNum > 0) {
    //                stv_dot.isVisible = true
    //            } else {
    //                stv_dot.isVisible = false
    //            }
            tab_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19f)
            tab_text.setTypeface(Typeface.DEFAULT_BOLD)
            tab_text.setTextColor(Color.parseColor("#e0000000"))
            tab_indicator.setImageResource(R.mipmap.icon_tab_indicator)

        }

        //要执行这一句才是真正将两者绑定起来
        mediator!!.attach()
    }

    override fun onInitView(savedInstanceState: Bundle?, intent: Intent?) {

    }

    private var ContactsviewModel: MainContactsListViewModel? = null

    @SuppressLint("FragmentLiveDataObserve")
    private fun initData() {
//        viewModel.getAllFriendList {
//            updateDotNum(it.data)
//        }

        mainViewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
        ContactsviewModel = ViewModelProviders.of(this)
            .get(MainContactsListViewModel::class.java)

        ContactsviewModel!!.loadAllFriendInfo()
        ContactsviewModel!!
            .getLoadAllFriendInfoResult()
            .observe(
                viewLifecycleOwner,
                object : Observer<Resource<List<FriendShipInfo?>>> {
                    override fun onChanged(listResource: Resource<List<FriendShipInfo?>>) {
                        if (listResource.status == Status.SUCCESS) {
                            if (listResource.data != null && listResource.data.size > 0) {
                                updateDotNum(listResource.data)
                            }
                        }
                    }
                })

        // 新朋友数量
        mainViewModel!!
            .newFriendNum
            .observe(
                viewLifecycleOwner,
                object : Observer<Int?> {
                    override fun onChanged(count: Int?) {
                        countNum = count!!
                        Log.e("contactNum33", count.toString())
                        if (count>0){
                            tabCommunity.getTabAt(1)!!.customView!!.findViewById<ShapeTextView>(R.id.stv_dot).isVisible = true
                        }else{
                            tabCommunity.getTabAt(1)!!.customView!!.findViewById<ShapeTextView>(R.id.stv_dot).isVisible = false
                        }
                    }
                })
    }


    /**
     * 更新未读状态数量
     *
     * @param list
     */
    fun updateDotNum(list: List<*>) {
        var dotNum = 0
        for (info in list) {
            var friendShipInfo: FriendShipInfo? = null
            if (info is FriendShipInfo) {
                friendShipInfo = info
            } else if (info is ListItemModel<*>) {
                val listItemModel = info
                if (listItemModel.data is FriendShipInfo) {
                    friendShipInfo = listItemModel.data as FriendShipInfo
                }
            }
            // 待处理状态时数量加1
            if (friendShipInfo != null
                && friendShipInfo.status == FriendStatus.RECEIVE_REQUEST.statusCode
            ) {
                dotNum++
            }
        }

        countNum = dotNum
        Log.e("updateDotNumcontactNum", dotNum.toString() + "")
        mainViewModel!!.setNewFriendNum(dotNum)
    }

    override fun onResume() {
        super.onResume()
        update()
    }

    private fun getXOffset(): Int {
        val marginEnd = ScreenUtils.dip2px(activity, 12f)
        val popSelfXOffset: Float = (resources.getDimension(R.dimen.seal_main_title_popup_width)
                - ivAdd!!.getWidth())
        return popSelfXOffset.toInt()
    }


    private fun update() {
        viewModel.getAppVersions(IMManager.getInstance().currentId, "2", Build.MANUFACTURER) {
            if (it.code == 200) {
                if (!TextUtils.isEmpty(it.data.version)) {
//                    var code = versionToInt(it.data.version!!)
                    var code = it.data.version!!.replace(".", "").trim().toInt()
                    Log.e("versionVersion", code.toString())
//                    if (s.toInt().compareTo(AppUtils.getAppVersionCode()) == 1) { //a>b
//                    }

                    if (it.data.updateType == 1) {//1直接下载  2 网址下载  3 应用市场
                        var isForce = 0
                        if (it.data.isForce == 1) {//强制更新
                            isForce = 2
                        } else {
                            isForce = 0
                        }
                        //下载apk
                        val info = DownloadInfo().setApkUrl(it.data.downloadUrl)
//                            .setFileSize(31338250)
                            .setProdVersionCode(code)
                            .setProdVersionName(it.data.version)
//                    .setMd5Check("68919BF998C29DA3F5BD2C0346281AC0")
                            .setForceUpdateFlag(isForce)
                            .setUpdateLog(it.data.intro)
                        AppUpdateUtils.getInstance().checkUpdate(info)
                    } else if (it.data.updateType == 3) {
                        jumpToAppStore(requireContext())
                    }
                } else {
//                    ToastUtils.showShort("已是最新版本")
                }

            } else {
                com.cxh.rmsq.utils.ToastUtils.showToast(it.msg)
            }

        }
    }

    private val changeCallback: OnPageChangeCallback = object : OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            //可以来设置选中时tab的大小
            val tabCount = tabCommunity!!.tabCount
            for (i in 0 until tabCount) {
                val tab = tabCommunity.getTabAt(i)
                if (tab != null) {
                    val customView = tab.customView
                    if (customView != null) {
                        val tab_text = tab.customView!!.findViewById<TextView>(R.id.tab_text)
                        val stv_dot = tab.customView!!.findViewById<ShapeTextView>(R.id.stv_dot)
                        val tab_indicator =
                            tab.customView!!.findViewById<ImageView>(R.id.tab_indicator)

                     /*   if (i == 1 && countNum > 0) {
                            stv_dot.isVisible = true
                        } else {
                            stv_dot.isVisible = false
                        }*/
                        //                        if (position == 0) {
//                            tab_text.setTextColor(Color.parseColor("#e0000000"));
//                            tab_indicator.setImageResource(R.mipmap.icon_tab_indicator);
//                        } else if (position == 1) {
//                            tab_text.setTextColor(Color.parseColor("#e0000000"));
//                            tab_indicator.setImageResource(R.mipmap.icon_tab_indicator);
//                        } else if (position == 2) {
//                            tab_text.setTextColor(Color.parseColor("#e0000000"));
//                            tab_indicator.setImageResource(R.mipmap.icon_tab_indicator);
//                        }else if (position == 3) {
//                            tab_text.setTextColor(Color.parseColor("#e0000000"));
//                            tab_indicator.setImageResource(R.mipmap.icon_tab_indicator);
//                        }
                        if (tab.position == position) {
                            tab_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19f)
                            tab_text.typeface = Typeface.DEFAULT_BOLD
                            tab_indicator.visibility = View.VISIBLE
                            tab_text.setTextColor(Color.parseColor("#e0000000"))
                        } else {
                            tab_text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
                            tab_text.typeface = Typeface.DEFAULT
                            tab_indicator.visibility = View.INVISIBLE
                            tab_text.setTextColor(Color.parseColor("#666666"))
                        }
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_START_CHAT -> mainViewModel!!.startPrivateChat(
                    data!!.getStringExtra(
                        IntentExtra.STR_TARGET_ID
                    )
                )

                REQUEST_START_GROUP -> {
                    val memberList = data!!.getStringArrayListExtra(IntentExtra.LIST_STR_ID_LIST)
                    SLog.i("MainActivity.TAG", "memberList.size = " + memberList!!.size)
                    val intent: Intent = Intent(
                        activity,
                        CreateGroupActivity::class.java
                    )
                    intent.putExtra(IntentExtra.LIST_STR_ID_LIST, memberList)
                    startActivity(intent)
                }

                else -> {}
            }
        }
    }

    override fun onStartChartClick() {
        val intent: Intent = Intent(activity, SelectSingleFriendActivity::class.java)
        startActivityForResult(intent, REQUEST_START_CHAT)
    }

    override fun onCreateGroupClick() {
        val intent: Intent = Intent(activity, SelectCreateGroupActivity::class.java)
        startActivityForResult(intent, REQUEST_START_GROUP)
    }

    override fun onAddFriendClick() {
        val intent: Intent = Intent(activity, AddFriendActivity::class.java)
        startActivity(intent)
    }

    override fun onScanClick() {
        if (ContextCompat.checkSelfPermission(
                requireActivity(),
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // 显示对话框告知用户权限使用目的
            val builder = AlertDialog.Builder(activity)
            builder.setTitle("权限申请")
                .setMessage("为了便于您使用扫码功能，我们需要访问您的相机权限。")
                .setPositiveButton("允许") { dialog, which ->
                    val permissionInfoDialog = Dialog(requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    permissionInfoTitle = resources.getString(R.string.permission_info_title_camera)
                    permissionInfoContent =
                        resources.getString(R.string.permission_info_content_camera)
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }
                    AppPermissionUtil.requestPermissions(
                        activity,
                        arrayOf<String>(Manifest.permission.CAMERA),
                        object : OnPermissionListener {
                            override fun onPermissionGranted() {
                                val intent = Intent(
                                    activity,
                                    ScanActivity::class.java
                                )
                                startActivity(intent)
                                permissionInfoDialog.dismiss()
                            }

                            override fun onPermissionDenied() {
                                permissionInfoDialog.dismiss()
                            }
                        })
                }
                .setNegativeButton("拒绝") { dialog, which ->
                    // 用户拒绝权限申请
                }
                .show()
        } else {
            // 已获得权限，执行相关操作
            val intent: Intent = Intent(activity, ScanActivity::class.java)
            startActivity(intent)
        }
    }
}